#include "FQFNetworkMonitorThread.h"
#include <QDateTime>
#include <QDebug>

FQFNetworkMonitorThread::FQFNetworkMonitorThread(FQFMedia *m)
{
	media = m;
	srand(QDateTime::currentDateTime().toString("sszzz").toInt());
}

FQFNetworkMonitorThread::~FQFNetworkMonitorThread()
{
}

bool FQFNetworkMonitorThread::getConnect()
{
	return isConnect;
}

void FQFNetworkMonitorThread::setRtspUrl(const char * url, StreamOpenMode openMode)
{
    strcpy_s(rtspUrl, url);
	streamOpenMode = openMode;
}

void FQFNetworkMonitorThread::setRtmpUrl(const char * url)
{
    strcpy_s(rtmpUrl, url);
    generatingRandomAddress();
}

void FQFNetworkMonitorThread::startMonitor()
{
	isMonitor = true;
	if (!this->isRunning())
		this->start();
}

void FQFNetworkMonitorThread::stopMonitor()
{
	isMonitor = false;
}

void FQFNetworkMonitorThread::realseMonitor()
{
	isExit = true;
}

QString FQFNetworkMonitorThread::getRtmpUrl()
{
	QString url = rtmpUrl;
    return url;
}

QString FQFNetworkMonitorThread::getRtmpIp()
{
    QString ip;
    for(int i = 7; i < 1024; i++)
    {
//        if((rtmpUrl[i] <= '9' && rtmpUrl[i] >= '0') || rtmpUrl[i] == '.')
//        {
//            ip.append(rtmpUrl[i]);
//        }
//        else
//            break;
        if(rtmpUrl[i] == '/')
            break;
        ip.append(rtmpUrl[i]);
    }
    return ip;
}

QString FQFNetworkMonitorThread::getRtmpKey()
{
    return key;
}

void FQFNetworkMonitorThread::run()
{
	while (!isExit)
	{
		if (!media)
		{
			msleep(10);
			continue;
		}
		if (!isMonitor)
		{
			msleep(10);
			continue;
		}
		bool ok = media->getTimeoutState();
		if (!ok)
		{
			bool bRe;
			bRe = media->openInStream(rtspUrl, streamOpenMode);
			if (!bRe)
			{
				isConnect = bRe;
				msleep(10000);
				continue;
			}

			if (streamOpenMode & StreamOpenMode::PushOnly)
			{
				bRe = media->openOutStream(rtmpUrl);
				if (!bRe)
				{
					isConnect = bRe;
                    updateRandomAddress();
                    msleep(10000);
                    continue;
				}
			}
			isConnect = bRe;
			continue;
		}
		isConnect = ok;
		msleep(1000);
	}
}

void FQFNetworkMonitorThread::generatingRandomAddress()
{
    int l = static_cast<int>(strlen(rtmpUrl));
    if(rtmpUrl[l-1] != '/')
    {
        rtmpUrl[l] = '/';
        rtmpUrl[l+1] = '\0';
        l++;
    }
    char temp;
    int i;
    key.clear();
    for (i = l; i < l + 4; i++)
	{
		temp = rand() % 52;
		rtmpUrl[i] = temp > 25 ? (temp -26 + 'a') : (temp + 'A');
        key.append(rtmpUrl[i]);
	}
	rtmpUrl[i] = '\0';
}
void FQFNetworkMonitorThread::updateRandomAddress()
{
    int l = static_cast<int>(strlen(rtmpUrl));
    char temp;
    int i;
    key.clear();
	for (i = l-8; i < l; i++)
	{
		temp = rand() % 52;
		rtmpUrl[i] = temp > 25 ? (temp - 26 + 'a') : (temp + 'A');
        key.append(rtmpUrl[i]);
	}
}
